package com.example.kt_wear_app.presentation.global

import com.example.kt_wear_app.presentation.dao.ResponseData
import com.example.kt_wear_app.presentation.utils.HttpRequestUtils
import com.example.kt_wear_app.presentation.utils.MqttUtils
import com.example.kt_wear_app.presentation.utils.SharedPreferencesUtils
import com.google.gson.Gson
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

// 初始化
fun init() {
    runBlocking {
        SharedPreferencesUtils.clear()
        goLogin()  // 先执行登录
        getUserInfo() // 登录完成后执行获取用户信息
        getAppInfo() // 获取系统配置
    }
}

/*
* 登录
* */
suspend fun goLogin() {
    return suspendCoroutine { continuation ->
        val getParams = mutableMapOf<String, Any>().apply {
            put("account", 13226092718)
            put("code", 8888)
            put("scene", 2)
            put("terminal", 6)
            put("password", "")
        }

        HttpRequestUtils.post("/login/account", getParams, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                continuation.resumeWith(Result.failure(e))
            }

            override fun onResponse(call: Call, response: Response) {
                try {
                    val responseData =
                        Gson().fromJson(response.body?.string(), ResponseData::class.java);
                    println(responseData);

                    if (responseData.code == 1) {
                        val token = responseData.data["token"].toString();
                        println(token)
                        SharedPreferencesUtils.putString("token", token);
                    }
                } catch (e: Exception) {
                    continuation.resumeWith(Result.failure(e))
                } finally {
                    continuation.resume(Unit) // 重要！恢复协程继
                }
            }
        })
    }
}

/*
* 获取用户信息
* */
suspend fun getUserInfo() {
    HttpRequestUtils.get("/user/info", null, object : Callback {
        override fun onFailure(call: Call, e: IOException) {
        }

        override fun onResponse(call: Call, response: Response) {
            try {
                val responseData =
                    Gson().fromJson(response.body?.string(), ResponseData::class.java);
                println(responseData);

                if (responseData.code == 1) {
                    val userInfo = responseData.data;
                    println(userInfo)
                    SharedPreferencesUtils.putString("userInfo", Gson().toJson(userInfo));
                }
            } catch (e: Exception) {
                println(e)
            }
        }
    })
//    }
}

suspend fun getAppInfo() {
    val getParams = mutableMapOf<String, Any>().apply {
        put("os", "android")
    }
    HttpRequestUtils.get("/app/config", getParams, object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            TODO("Not yet implemented")
        }

        override fun onResponse(call: Call, response: Response) {
            try {
                val responseData =
                    Gson().fromJson(response.body?.string(), ResponseData::class.java);
                println(responseData);

                if (responseData.code == 1) {
                    val config: Map<String, Any> = responseData.data["config"] as Map<String, Any>;
                    val mqtt: Map<String, Any> = config["mqtt"] as Map<String, Any>;
                    val tencent: Map<String, Any> = config["tencent"] as Map<String, Any>;
                    SharedPreferencesUtils.putString("mqtt", Gson().toJson(mqtt));
                    SharedPreferencesUtils.putString("tencent", Gson().toJson(tencent));

                    MqttUtils.initClient(
                        mapOf(
                            "server" to mqtt["server"],
                            "clientId" to mqtt["clientId"]
                        )
                    )

                }
            } catch (e: Exception) {
                println(e)
            }
        }

    })
}
